package com.antler.mobilesniffer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

import com.antler.utils.MyLog;

import java.text.SimpleDateFormat;

public class PhoneCallReceiver extends BroadcastReceiver {
    protected static final String TAG = "[ANTLER]" + PhoneCallReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        MyLog.log(TAG, "onReceive: " + intent);

        if (null != intent) {
            String action = intent.getAction();
            if (null != action) {
                if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
                    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                    String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    String receiveTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());

                    MyLog.log(TAG, String.format("time:%s, state:%s, number:%s", receiveTime, state, incomingNumber));

                    Intent intentPhoneCall = new Intent(context, MainService.class);

                    if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {

                    } else if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        intentPhoneCall.setAction(MainService.ACTION_FORWARD_CALL);
                        intentPhoneCall.putExtra(MainService.CALL_RECEIVE_TIME, receiveTime);
                        intentPhoneCall.putExtra(MainService.CALL_NUMBER, incomingNumber);
                    } else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {

                    }

                    context.startService(intentPhoneCall);

                } else if(action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {

                }
            }
        }
    }
}
